﻿using _1._8._2015_AuthExample.Data;
using _1._8._2015_AuthExample.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using _1._8._2015_AuthExample.Adapters;

namespace _1._8._2015_AuthExample.Controllers
{
    [Authorize]
    public class AddressController : Controller
    {
        private IAddressAdapter _adapter;

        public AddressController()
        {
            _adapter = AddressAdapterFactory.GetAddressAdapter();
        }

        public AddressController(IAddressAdapter adapter)
        {
            _adapter = adapter;
        }

        // GET: Address
        public ActionResult Index()
        {
            AddressIndexViewModel model = new AddressIndexViewModel();

            if (User.IsInRole("General"))
            {
                string userId = User.Identity.GetUserId();
                model.Addresses = _adapter.GetAddresses(userId);
            }
            else
            {
                model.Addresses = _adapter.GetAddresses();
            }

            return View(model);
        }

        [Authorize(Roles=Roles.ADMINISTRATOR)]
        public ActionResult AdminOnly()
        {
            return View();
        }

        [Authorize(Roles=Roles.ADMINISTRATOR)]
        public ActionResult CreateAddress()
        {
            CreateAddressViewModel model = new CreateAddressViewModel();
            model.Users = _adapter.HydrateUserLookUpModels();
            
            return View(model);
        }

        [HttpPost]
        public ActionResult UpdateAddress(UpdateAddressViewModel model)
        {
            _adapter.UpdateAddress(model);
            return View();
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult CreateAddress(CreateAddressViewModel model)
        {
            if (!ModelState.IsValid)
            {
                model.Users = _adapter.HydrateUserLookUpModels();
                return View(model);
            }

            //Create - Save address
            _adapter.CreateAddress(model);

            return RedirectToAction("Index");
        }
    }
}